from functools import wraps

from DrissionPage.errors import ElementNotFoundError

from util.mylog import my_logger


def crawler_exception_handler(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except ElementNotFoundError as e:
            my_logger.warning(f"{type(e)} in {func.__name__}: {e} / {args[-1] if args else ''}")
            return False, args[-1]
        except Exception as e:
            my_logger.trace(f"{type(e)}  in {func.__name__}: {e} / {args[-1] if args else ''}")
            my_logger.error(f"{type(e)}  in {func.__name__}: {e} / {args[-1] if args else ''}")
            return False, args[-1]
    return wrapper
def async_crawler_exception_handler(func):
    @wraps(func)
    async def wrapper(*args, **kwargs):
        try:
            return await func(*args, **kwargs)
        except ElementNotFoundError as e:
            my_logger.warning(f"{type(e)} in {func.__name__}: {e} / {args[-1] if args else ''}")
            return False, args[-1]
        except Exception as e:
            my_logger.trace(f"{type(e)}  in {func.__name__}: {e} / {args[-1] if args else ''}")
            my_logger.error(f"{type(e)}  in {func.__name__}: {e} / {args[-1] if args else ''}")
            return False, args[-1]
    return wrapper